package com.wsz.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wsz.pojo.AclUser;
import com.wsz.pojo.R;
import com.wsz.pojo.vo.AclUserVo;
import com.wsz.ucenter.service.AclUserService;
import com.wsz.ucenter.mapper.AclUserMapper;
import com.wsz.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
* @author wangs
* @description 针对表【acl_user】的数据库操作Service实现
* @createDate 2023-03-10 23:10:17
*/
@Service
public class AclUserServiceImpl extends ServiceImpl<AclUserMapper, AclUser>
    implements AclUserService{

    @Override
    public R login(AclUser aclUser) {
        String username = aclUser.getUsername();
        String password = aclUser.getPassword();

        System.out.println(username+password);

        if(username == null) {
            return R.error().message("用户名为空");
        }

        if(password == null) {
            return R.error().message("密码为空");
        }

        AclUser user = getOne(new QueryWrapper<AclUser>().eq("username", username));
        if(user == null) return R.error().message("用户不存在，请检查用户名是否输入错误");

        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();

        if(!bc.matches(password,user.getPassword())){
            return R.error().message("密码错误");
        }

        String accessToken = JwtUtils.createAccessToken(user.getUsername(), user.getId(), UUID.randomUUID().toString().substring(0,4));

        AclUserVo aclUserVo = new AclUserVo();

        BeanUtils.copyProperties(user,aclUserVo);

        return R.ok().data("access",accessToken).data("userInfo",aclUserVo);
    }
}




